package com.my.utils;

import com.my.security.TokenInfo;
import com.my.sys.model.SysUser;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.codec.Hex;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;

/**
 * Created by 80002023 on 2016/6/13.
 */
public class TokenUtils {

    public final static String TOKEN = "token";

    public static final String MAGIC_KEY = "demo";

    public static TokenInfo generate(SysUser user, int days) {
        if (days <= 0) {
            days = 7;
        }
        /* Expires in one hour */
        Long expires = System.currentTimeMillis() + 1000L * 60 * 60 * days;

        StringBuilder keyBuilder = new StringBuilder();
        keyBuilder.append(TOKEN);
        keyBuilder.append(":");
        keyBuilder.append(user.getUsername());
        //keyBuilder.append(":");
        //keyBuilder.append(expires);
        //keyBuilder.append(":");
        //keyBuilder.append(TokenUtils.computeSignature(user.getUsername(), expires));
        String token = TokenUtils.computeSignature(user.getUsername(), expires);
        return new TokenInfo(user.getUsername(), new Date(expires), token);
    }


    public static String computeSignature(String username, Long expires) {
        StringBuilder signatureBuilder = new StringBuilder();
        signatureBuilder.append(username);
        signatureBuilder.append(":");
        signatureBuilder.append(expires);
        //signatureBuilder.append(":");
        //signatureBuilder.append(user.getPassword());
        signatureBuilder.append(":");
        signatureBuilder.append(TokenUtils.MAGIC_KEY);

        MessageDigest digest;
        try {
            digest = MessageDigest.getInstance("MD5");

        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException("No MD5 algorithm available!");
        }

        return new String(Hex.encode(digest.digest(signatureBuilder.toString().getBytes())));
    }

    public static String generate(UsernamePasswordToken token) {
        long expires = System.currentTimeMillis() + 1000L * 60 * 60 * 7;

        StringBuilder tokenBuilder = new StringBuilder();
        tokenBuilder.append(token.getUsername());
        tokenBuilder.append(":");
        tokenBuilder.append(expires);
        tokenBuilder.append(":");
        tokenBuilder.append(TokenUtils.computeSignature(token.getUsername(), expires));

        return tokenBuilder.toString();
    }
}
